<template>
  <!--订单选择-->
  <a-modal
    title="选择精华液"
    :visible.sync="bottleShow"
    @ok="addPPRelationOk"
    :confirm-loading="confirmLoading"
    @cancel="handleCancel"
    width="80%"
    class="procedure-modal"
  >
    <div class="operation-search">
      <a-form layout="inline" :form="searchItem">
        <a-form-item label="批次号：">
          <a-input
            :allowClear="true"
            placeholder="请输入"
            v-model="searchItem.batchNo"
          />
        </a-form-item>
        <a-form-item>
          <a-button class="default-button" @click="getPackingPlansListFun">
            查询
          </a-button>
        </a-form-item>
        <a-form-item v-for="(group, index) in selectedGroups" :key="index">
          <span>{{ group.MaterialCode }}：</span>
          <span class="total-amount">需求数量 {{ group.ReqQty }} </span>
          <span class="total-amount">分配数量 {{ group.DistributeQty }} </span>
          <span
            class="total-amount"
            :class="{ negative: group.ReqQty - group.DistributeQty < 0 }"
          >
            剩余 {{ (group.ReqQty - group.DistributeQty).toFixed(3) }}
          </span>
        </a-form-item>
      </a-form>
    </div>
    <div style="height: 400px">
      <a-table
        :columns="orderColums"
        :row-key="(record) => record.num"
        :data-source="orderList"
        :loading="loading1"
        :pagination="false"
        :scroll="{ x: 700, y: 350 }"
        size="middle"
        :rowClassName="getRowClassName"
      >
        <template slot="IfRecharged" slot-scope="text, record">
          <a-checkbox disabled v-model="record.IfRecharged"></a-checkbox>
        </template>
        <template slot="IsQCLock" slot-scope="text, record">
          <a-checkbox disabled v-model="record.IsQCLock"></a-checkbox>
        </template>
        <!-- 新增质检状态自定义渲染模板 -->
        <template slot="QMResult" slot-scope="text, record">
          <a-tag
            :color="getQMResultColor(record.QMResult)"
            v-if="record.QMResult !== undefined"
          >
            {{ getQMResultText(record.QMResult) }}
          </a-tag>
        </template>
        <template slot="DistributeQty" slot-scope="text, record">
          <a-input-number
            id="inputNumber"
            :allowClear="true"
            :min="0"
            :max="record.ToDistributeQty"
            placeholder="请输入"
            v-model="record.DistributeQty"
            @change="updateSelectedTotalQty"
          />
        </template>
        <template slot="action" slot-scope="text, record">
          <div class="chart-manage">
            <general-button
              :disabled="!record.AllocatedQty > 0"
              @operation="alreadySmgrShow(record)"
              btn-text="已分配"
              class="small-button"
            ></general-button>
          </div>
        </template>
      </a-table>
    </div>
    <!-- 查看已预分配弹窗 -->
    <already-form
      v-model="alreadyShow"
      :plan-no="alreadyData.PlanNo"
      :material-code="alreadyData.MaterialCode"
      :batch-no="alreadyData.BatchNo"
      @colse="alreadyShow = false"
    ></already-form>
  </a-modal>
</template>

<script>
import { debounce } from "@/common/debounce";
import {
  getSemiMGoodsRecordRequest,
  insSemiMGoodsDistributeDetail,
  getSemiMGoodsRecordsByDistribute,
} from "@/api/SemiMGoodsDistributeDetail/index";
import GeneralButton from "@/components/be-current-btn.vue";
import AlreadyForm from "../preAllocationDetails/essence-form-already.vue";
export default {
  components: {
    GeneralButton,
    AlreadyForm,
  },
  props: {
    bottleShow: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: "",
    },
    semiMGoodsDistributeDetailDtos: {
      type: Array,
      default: [],
    },
  },
  model: {
    prop: "bottleShow",
    event: "close",
  },

  data() {
    return {
      selectedGroups: [], // 新增分组数据
      totalDistributeQty: 0,
      remainingDistributeQty: 0, // 添加剩余分配数
      colResize: {
        isDragging: false,
        startX: 0,
        startWidth: 0,
        currentColIndex: -1,
      },
      confirmLoading: false, //modal的loading
      defaulttimeList: [], //默认时间
      searchItem: {
        pageRequestModel: {
          pageIndex: 1,
          pageSize: 30,
        },
        materialNameCode: null,
        batchNo: null,
      }, //搜索参数
      orderColums: [
        {
          title: "序号",
          dataIndex: "num",
          fixed: "left",
          width: 50,
          align: "center",
        },
        {
          title: "销售单号",
          dataIndex: "SellOrderNo",
          sorter: true,
          align: "center",
          width: 120,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 1),
            },
          }),
        },
        {
          title: "投料单号",
          dataIndex: "PlanNo",
          align: "center",
          ellipsis: true,
          width: 120,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 2),
            },
          }),
        },
        {
          title: "精华液编码",
          dataIndex: "MaterialCode",
          sorter: true,
          align: "center",
          width: 100,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 3),
            },
          }),
        },
        {
          title: "精华液名称",
          dataIndex: "MaterialName",
          align: "center",
          width: 300,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 4),
            },
          }),
        },
        {
          title: "批次号",
          dataIndex: "BatchNo",
          align: "center",
          ellipsis: true,
          width: 150,
          customHeaderCell: () => ({
            style: { position: "relative" },
            on: {
              mousedown: (e) => this.handleResizeStart(e, 5),
            },
          }),
        },
        {
          title: "当前库存",
          dataIndex: "CurQty",
          align: "center",
          ellipsis: true,
          width: 100,
        },
        {
          title: "是否回抽料",
          dataIndex: "IfRecharged",
          key: "IfRecharged",
          ellipsis: true,
          align: "center",
          width: 100,
          scopedSlots: { customRender: "IfRecharged" },
        },
        {
          title: "质检状态",
          dataIndex: "QMResult",
          align: "center",
          ellipsis: true,
          width: 100,
          scopedSlots: { customRender: "QMResult" }, // 添加自定义渲染槽位
        },
        {
          title: "质检锁定",
          dataIndex: "IsQCLock",
          align: "center",
          ellipsis: true,
          width: 100,
          scopedSlots: { customRender: "IsQCLock" },
        },
        {
          title: "待分配数量",
          dataIndex: "ToDistributeQty",
          align: "center",
          width: 100,
        },

        {
          title: "已分配数量",
          dataIndex: "AllocatedQty",
          align: "center",
          ellipsis: true,
          width: 100,
        },

        {
          title: "生产日期",
          dataIndex: "CreateDt",
          align: "center",
          ellipsis: true,
          width: 100,
        },
        {
          title: "质检有效期",
          dataIndex: "ValidityDt",
          align: "center",
          ellipsis: true,
          width: 150,
        },
        {
          title: "分配数量",
          key: "DistributeQty",
          scopedSlots: { customRender: "DistributeQty" },
          fixed: "right",
          width: 150,
        },
        {
          title: "操作",
          dataIndex: "operate",
          width: 60,
          align: "center",
          fixed: "right",
          scopedSlots: { customRender: "action" },
        },
      ],
      orderList: [], //工单选择列表
      orderItem: { batchNo: null },
      orderListTotal: 0,
      pageSizeOptions: ["30", "50", "100", "200", "500", "1000"], //分页
      loading1: false,
      alreadyShow: false, //已分配弹窗
      alreadyData: {}, //已分配的数据
    };
  },
  methods: {
    // 添加状态文本转换方法
    getQMResultText(value) {
      const map = { 0: "不合格", 1: "合格", 4: "待检" };
      return map[value] || "未知";
    },
    // 添加状态颜色转换方法
    getQMResultColor(value) {
      const colorMap = { 0: "#ff4d4f", 1: "#52c41a", 4: "#958900" };
      return colorMap[value] || "#bfbfbf";
    },
    //字体颜色
    getRowClassName(record) {
      const sevenDaysAgo = new Date().getTime() + 7 * 24 * 60 * 60 * 1000; // 计算7天前的时间戳（毫秒）
      // 根据行的某些条件来返回不同的类名
      if (new Date(record.ValidityDt).getTime() < new Date().getTime()) {
        return "rowRedClass";
      }
      if (new Date(record.ValidityDt).getTime() < sevenDaysAgo) {
        return "rowOrangeClass";
      }
      if (record.QMResult == 4 || record.IsQCLock == 1) {
        return "rowYellowClass";
      } else {
        return ""; // 或者返回null，表示不应用任何类名
      }
    },
    // 列宽调整相关方法
    handleResizeStart(e, colIndex) {
      e.preventDefault();
      this.colResize = {
        isDragging: true,
        startX: e.clientX,
        startWidth: this.orderColums[colIndex].width,
        currentColIndex: colIndex,
      };
      // 添加事件监听
      document.addEventListener("mousemove", this.handleResizing);
      document.addEventListener("mouseup", this.handleResizeEnd);
    },

    handleResizing(e) {
      if (!this.colResize.isDragging) return;

      const delta = e.clientX - this.colResize.startX;
      const newWidth = Math.max(50, this.colResize.startWidth + delta);

      // 更新对应的列数组
      const newColumns = this.orderColums.map((col, index) => {
        if (index === this.colResize.currentColIndex) {
          return { ...col, width: newWidth };
        }
        return col;
      });

      this.orderColums = newColumns;
    },

    handleResizeEnd() {
      this.colResize.isDragging = false;
      this.colResize.currentColIndex = -1; // 重置当前列索引
      document.removeEventListener("mousemove", this.handleResizing);
      document.removeEventListener("mouseup", this.handleResizeEnd);
    },
    /** 修改精华液预分配 */
    async addPPRelationOk() {
      this.confirmLoading = true;
      try {
        this.essenceItem = this.orderList.filter(
          (item) => item.DistributeQty > 0
        );

        if (!this.essenceItem || this.essenceItem.length == 0) {
          this.$message.error("请输入分配数量");
        }

        this.essenceItem.forEach((item) => {
          item.SemiMGoodsDistributeID = this.id;
        });

        let res = await insSemiMGoodsDistributeDetail(this.essenceItem);
        if (res.Status == 10000) {
          this.$message.success("添加成功");
          this.$emit("up-data");
          this.$emit("close", false);
        } else {
          this.$message.error(res.Message);
        }
      } catch (e) {
        this.$message.error(e);
      } finally {
        this.confirmLoading = false;
      }
    },
    //获取单据列表
    getPackingPlansListFun: debounce(async function () {
      let that = this;
      that.loading1 = true;
      try {
        that.searchItem.SemiMGoodsRecordDistributeID = this.id;

        let res = await getSemiMGoodsRecordsByDistribute(that.searchItem);
        if (res.Status == 10000) {
          that.orderList = res.Data.SemiMGoodsDistributeDetails;
          if (that.orderList) {
            that.orderList.forEach((item, index) => {
              item.num = index + 1;
              item.batchNo = item.BatchNo;
              item.id = item.MaterialCode + item.BatchNo + item.PlanNo;
              item.CreateDt = that.dateExt.showDate(item.CreateDt);
              item.ValidityDt = that.dateExt.showDateTime(item.ValidityDt);
            });
          }
          if (res.Data.SemiMGoodsDistributes) {
            that.selectedGroups = res.Data.SemiMGoodsDistributes;
          }
        } else {
          that.$message.error(res.Message);
        }
      } catch {
      } finally {
        that.loading1 = false;
      }
    }),

    //关闭弹窗
    handleCancel() {
      this.orderItem = {};
      this.$emit("close", false);
    },
    //确认添加/修改
    handleOk() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
        }
      });
    },
    // 添加行样式判断方法
    getRowClassName(record) {
      if (new Date(record.ValidityDt).getTime() < new Date().getTime()) {
        return "expired-row";
      }
      return "";
    },
    // 确保统计方法包含所有分配数据
    updateSelectedTotalQty() {
      // 按物料编码分组统计总分配量
      const distributeMap = this.orderList.reduce((acc, item) => {
        const key = item.MaterialCode;
        acc[key] = (acc[key] || 0) + Number(item.DistributeQty || 0);
        return acc;
      }, {});

      // 更新selectedGroups中的分配数量
      this.selectedGroups = this.selectedGroups.map((group) => ({
        ...group,
        DistributeQty: (
          distributeMap[group.MaterialCode] + group.AllocatedQty || 0
        ).toFixed(3),
      }));
    },
    //已分配精华液
    alreadySmgrShow(item) {
      this.alreadyShow = true;
      this.alreadyData = item;
    },
  },
  created() {
    let that = this;
  },
  watch: {
    bottleShow: {
      handler(newV, oldV) {
        if (newV) {
          this.getPackingPlansListFun();
        }
      },
      immediate: true, // 重点
      deep: true, // 重点
    },
  },
};
</script>

<style lang="less" scoped>
// 添加列宽拖曳样式
::v-deep .ant-table-thead > tr > th {
  position: relative;
  user-select: none;

  &::after {
    content: "";
    position: absolute;
    right: -3px !important; // 扩大可拖拽区域
    top: 0;
    z-index: 1;
    width: 5px;
    height: 100%;
    cursor: col-resize;
    background-color: transparent;
    transition: background-color 0.3s;
  }

  &:hover::after {
    background-color: #1890ff;
  }
}

.ant-table-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.procedure-modal {
  .title {
    border-bottom: 1px solid #eeeeee;
    padding: 0.625rem 0;
    margin-bottom: 0.625rem;
  }
  .production-reporting {
    border-bottom: 1px solid #eeeeee;
    padding: 0.625rem 0;
    height: 1000px;
    margin-bottom: 0.625rem;
    .name {
      font-size: 1.125rem;
      font-weight: bold;
    }
  }
  .table-box {
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    .left {
      flex: 1;
    }
    .right {
      flex: 1;
    }
    .center {
      display: flex;
      flex-direction: column;
      margin: 0 1.25rem;
    }
    .search {
      margin: 0.625rem 0;
    }
    .name {
      font-size: 1.125rem;
      font-weight: bold;
    }
  }
  .searchrow {
    display: flex;
    justify-content: flex-end;
    padding: 2px;
  }
  .operation-search {
    display: flex;
    //justify-content: flex-end;
    border-bottom: 2px solid #f0f2f5;
    //margin-bottom: 0.9375rem;
    .selectwidth {
      width: 15rem;
    }
    .selectrightwidth {
      width: 7rem;
    }
  }
}
/deep/.ant-table-body {
  &::-webkit-scrollbar {
    margin: 0.2rem;
    //整体样式
    height: 0.4125rem;
    width: 0.3rem;
  }

  &::-webkit-scrollbar-thumb {
    //滑动滑块条样式
    border-radius: 0.625rem;
    -webkit-box-shadow: inset 0 0 1px rgba(0, 0, 0, 0.2);
    background: #009a9a;
    // background: rgba(2, 35, 60, 1);
  }

  &::-webkit-scrollbar-track {
    //轨道的样式
    -webkit-box-shadow: 0;
    border-radius: 0.625rem;
    background: #ccc;
  }

  &::-webkit-scrollbar-corner {
    background: red;
  }
}

// 添加过期行样式
::v-deep .expired-row {
  color: #ff4d4f;
}

.total-amount {
  display: inline-flex;
  align-items: center;
  padding: 4px 12px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  margin-left: 8px;
  font-size: 14px;
  color: #1890ff;
  font-weight: 500;
  min-width: 80px;
  justify-content: center;

  &.negative {
    color: #ff4d4f;
  }
}
.small-button {
  padding: 0 8px;
  height: 22px;
  line-height: 22px;
  font-size: 12px;
  border-radius: 2px;
  margin-right: 8px;
  text-align: center;
  cursor: pointer;
  display: flex;
  align-items: center;
}
</style>
